#!/usr/bin/env python3
#
# Copyright 2017 Jeff Bush
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


#
# Generate a C header file with vertices and indices for a 3D torus.
#

import math

OUTER_STEPS = 20
INNER_STEPS = 16
INNER_DIAMETER = 0.2
OUTER_DIAMETER = 0.5

print('// Autogenerated by mktorus.py')
print('const int kNumTorusVertices = %d;' % (OUTER_STEPS * INNER_STEPS))
print('const float kTorusVertices[] = {')

for outer_step in range(OUTER_STEPS):
    outer_r = outer_step * 2.0 * math.pi / OUTER_STEPS
    for inner_step in range(INNER_STEPS):
        inner_r = inner_step * 2.0 * math.pi / INNER_STEPS

        inner_dist = math.cos(inner_r) * INNER_DIAMETER
        x = math.sin(outer_r) * (inner_dist + OUTER_DIAMETER)
        y = math.cos(outer_r) * (inner_dist + OUTER_DIAMETER)
        z = math.sin(inner_r) * INNER_DIAMETER

        center_x = math.sin(outer_r) * OUTER_DIAMETER
        center_y = math.cos(outer_r) * OUTER_DIAMETER

        normal_x = (x - center_x) / INNER_DIAMETER
        normal_y = (y - center_y) / INNER_DIAMETER
        normal_z = z / INNER_DIAMETER

        print('\t%#0.10gf, %#0.10gf, %#0.10gf, %#0.10gf, %#0.10gf, %#0.10gf,' %
              (x, y, z, normal_x, normal_y, normal_z))

print('};')

#
# Build index list
#

print('const int kNumTorusIndices = %d;' % (OUTER_STEPS * INNER_STEPS * 6))
print('const int kTorusIndices[] = {')


def step_wrapping_outer(index):
    return (index + 1) % OUTER_STEPS


def step_wrapping_inner(index):
    return (index + 1) % INNER_STEPS

for outer_step in range(OUTER_STEPS):
    for inner_step in range(INNER_STEPS):
        print('\t%d, %d, %d,' % (
            (outer_step * INNER_STEPS) + inner_step,
            (outer_step * INNER_STEPS) + step_wrapping_inner(inner_step),
            step_wrapping_outer(outer_step) * INNER_STEPS + step_wrapping_inner(inner_step)))

        print('\t%d, %d, %d,' % (
            step_wrapping_outer(outer_step) * INNER_STEPS +
            step_wrapping_inner(inner_step),
            step_wrapping_outer(outer_step) * INNER_STEPS + inner_step,
            outer_step * INNER_STEPS + inner_step))

print('};')
